#-*- coding: utf-8 -*-
#! /usr/bin/python

import sys
import ConfigParser
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import httplib
import re
import base64
import time
import win32api
import win32con
import hashlib
import win32gui

reload(sys)
sys.setdefaultencoding("utf-8")


def getMacAdd():
    
    '''
    获得mac地址
    '''
    import uuid
    node = uuid.getnode()
    mac = uuid.UUID(int = node).hex[-12:]
    return mac


def checksn(soft, sn):
    '''
    检查sn是否正常
    '''
    MAC = getMacAdd()
    #print makesn(soft, MAC)
    if(sn == makesn(soft, MAC)):        
        return True
    else:
        keystr = 'SOFTWARE\\Microsoft\\Internet Explorer\\Main'
        value = getRegValue1(keystr, 'Expand Alt Text')
        value = (str(value)).split("'")[1]        
        if(int(value)>=10):
            print 'Try times Out!! Please contact QQ:894610580 to buy'
            win32gui.MessageBox(0, '你的使用次数达到上限10次，请联系客服QQ:894610580购买！'.decode('utf-8'), 'Notice!', 0)
            return False
        else:
            value = str(int(value)+1)
            win32gui.MessageBox(0, '试用次数达到'+value+'次哦亲：）！'.decode('utf-8'), 'Notice!', 0)
            setRegValue1(keystr, 'Expand Alt Text', value)
            return True

        
def makesn(soft, MAC):
    '''
    soft是软件的发布版exe名字
    '''
    print soft
    print MAC
    soft = soft + MAC
    x = hashlib.sha224((hashlib.md5('jhf')).hexdigest()+'jhfaixiaobao'+soft)
    return x.hexdigest()


def setRegValue1(keystr, vname, value):
    '''
    设置某个注册表项的值，不存在则先添加项再设置值
    '''
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(kv==value):
            return True
        else:
            win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
            win32api.RegCloseKey(key)
            return True            
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
        win32api.RegCloseKey(key)
        return True


def getRegValue1(keystr, vname):
    '''
    读取某个注册表项的值，返回值或者设置为1
    '''
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(str(kv)=="('no', 1)"):
            win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, '1')
            win32api.RegCloseKey(key)
            return "('1',1)"
        else:
            return kv            
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, '1')
        win32api.RegCloseKey(key)
        return True


def setRegValue(keystr, vname, value):
    '''
    设置某个注册表项的值，不存在则先添加项再设置值
    '''
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keystr, 0, win32con.KEY_ALL_ACCESS)
    try:
        kv = win32api.RegQueryValueEx(key, vname)
        if(kv==value):
            return True
        else:
            win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
            win32api.RegCloseKey(key)
    except:
        win32api.RegSetValueEx(key, vname, 0, win32con.REG_SZ, value)
        win32api.RegCloseKey(key)
        return True


def lgRouter():
    # 192.168.1.1
    conn = httplib.HTTPConnection("192.168.1.1")
    name = 'admin'
    passwd = 'admin'
    # set request headers
    headers = {"User-Agent": "python host",
        "Content-type": "application/x-www-form-urlencoded",
        "Authorization": "Basic %s" % base64.encodestring('%s:%s' % (name, passwd))[:-1],
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-cn,zh;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Charset": "GB2312,utf-8;q=0.7,*;q=0.7",
        "Connection": "keep-alive"}

    # get status page
    conn.request("GET", "/userRpm/StatusRpm.htm", "", headers)
    response = conn.getresponse()
    keyword = re.search(' wanPara [^\)]*?\)', response.read())
    response.close()
    conn.close()

    # search the public ip address
    found = 0
    publicIP = ""
    if keyword:
        arr = re.findall('([\d]*?,)|(\"[^\"]*?\",)', keyword.group(0))
        if arr:
            if len(arr) > 3:
                publicIP = re.search('(?<=\")[^\"]*?(?=\")', arr[2][1])
                if publicIP:
                    publicIP = publicIP.group(0)
                    found = 1

    if found == 1:
        return publicIP
    else:
        return "Error"


def diconectRouter():
    conn = httplib.HTTPConnection("192.168.1.1")
    name = 'admin'
    passwd = 'admin'
    # set request headers
    headers = {"User-Agent": "python host",
        "Content-type": "application/x-www-form-urlencoded",
        "Authorization": "Basic %s" % base64.encodestring('%s:%s' % (name, passwd))[:-1],
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-cn,zh;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Charset": "GB2312,utf-8;q=0.7,*;q=0.7",
        "Connection": "keep-alive"}  

    sparam = "?Disconnect=%B6%CF%20%CF%DF&wan=1"    
    conn.request("GET", "/userRpm/StatusRpm.htm"+sparam, "", headers)    
    response = conn.getresponse()
    keyword = re.search(' wanPara [^\)]*?\)', response.read())
    response.close()
    conn.close()
    
    # search the public ip address
    found = 0
    publicIP = ""
    if keyword:
        arr = re.findall('([\d]*?,)|(\"[^\"]*?\",)', keyword.group(0))
        if arr:
            if len(arr) > 3:
                publicIP = re.search('(?<=\")[^\"]*?(?=\")', arr[2][1])
                if publicIP:
                    publicIP = publicIP.group(0)
                    found = 1
    if(publicIP == '0.0.0.0'):
        #print "disconect!"
        return True
    else:
        #print publicIP
        return False


def connectRouter():
    conn = httplib.HTTPConnection("192.168.1.1")
    name = 'admin'
    passwd = 'admin'
    # set request headers
    headers = {"User-Agent": "python host",
        "Content-type": "application/x-www-form-urlencoded",
        "Authorization": "Basic %s" % base64.encodestring('%s:%s' % (name, passwd))[:-1],
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "zh-cn,zh;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Charset": "GB2312,utf-8;q=0.9,*;q=0.8",
        "Referer": "http://192.168.1.1/userRpm/StatusRpm.htm",
        "Host": "192.168.1.1",
        "Connection": "keep-alive"}  

    sparam = "?Connect=%C1%AC%20%BD%D3&wan=1"    
    conn.request("GET", "/userRpm/StatusRpm.htm"+sparam, "", headers)
    conn.close()
    time.sleep(0.9)
    rt = lgRouter()

    if(rt=="0.0.0.0"):
        print "Status is disconect"        
    else:
        if(rt=="Error"):
            print "Status is Error"
        else:
            print "Status is conect,ip is "+rt
    return rt


def changeip():
    rt = lgRouter()
    if(rt=="0.0.0.0"):
        print "Status is disconect"
    else:
        if(rt=="Error"):
            print "Status is Error"
        else:
            print "Status is conect,ip is "+rt
    rt = diconectRouter()
    if(rt):
        print "Disconect the Router Successfully"
    time.sleep(0.5)
    rtt = connectRouter()
    i =  5
    while((rtt == rt) and (i>0)):
        diconectRouter()
        rtt = connectRouter()
        i = i - 1


def logoutTb():
    '''
    logout from taobao
    '''
    lurl = "http://login.taobao.com/member/logout.jhtml?spm=a1z02.1.0.6.wXTWrc&amp;f=top&amp;out=true&amp;redirectURL=http%3A%2F%2Fi.taobao.com%2Fmy_taobao.htm%3Fnekot%3Ds6S6%252BtfTtcTQodHy1351908154890"
    chrome.get(lurl)


def loginTb(username,password):
    '''
    jhfnetboy@gmail.com create to login taobao
    '''
    #chrome.delete_all_cookies()
    lgurl = 'https://login.taobao.com/member/login.jhtml'
    chrome.get(lgurl)
    #set username and password
    try:
        chrome.find_element_by_class_name('nickx').click()
    except:
        pass
    try:
        #chrome.execute_script("document.getElementByName('TPL_username').value = '11'")
        #uname = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_name("TPL_username"))
        #uname = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("TPL_username_1"))
        uname = chrome.find_element_by_id("TPL_username_1")
        uname.send_keys(username.decode('gbk'))
    except:
        print 'fail to get element TPL_username'
    try:
        ckbox = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("J_SafeLoginCheck"))
        ckbox.click()
    except:
        print 'fail to get element J_SafeLoginCheck'
    try:
        pword = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_name("TPL_password"))
        pword.send_keys(password)
    except:
        print 'fail to get element TPL_password'
    try:
        btn = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("J_SubmitStatic"))
        btn.click()
    except:
        print 'fail to get element J_SubmitStatic'
    try:
        lgok = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_link_text(username.decode('gbk')))
        return True
    except:
        return False


def initConfig(filename):
    '''
    去掉文件头BOM等
    Window下用记事本打开配置文件并修改保存后，编码为UNICODE
    或UTF-8的文件的文件头
    #会被相应的加上\xff\xfe（\xff\xfe）或\xef\xbb\xbf
    '''
    import re
    content = open(filename).read()
    content = re.sub(r"\xfe\xff", "", content)
    content = re.sub(r"\xff\xfe", "", content)
    content = re.sub(r"\xef\xbb\xbf", "", content)
    open(filename, 'w').write(content)


def logit(content, filename='log.txt'):
    '''
    逐行添加日志，每行一个回车
    头部是时间
    '''
    file = open(filename, 'a')
    try:
        file.write('\r\n'+content+'\r\n')
    finally:
        file.close()


def pai(item, count):
    '''
    buy url item
    '''
    time.sleep(0.9)
    chrome.stop_client()
    #退出支付宝
    chrome.get('https://auth.alipay.com/login/logout.htm')     
    chrome.get(item)
    time.sleep(1.5)
    chrome.switch_to_frame("J_BundleDetail")
    chrome.stop_client()  
    try:#submit form，在产品页面，点击购买
        fm = chrome.find_element_by_id('J_FrmBid')
        fm.submit()
    except:
        print 'fail to get element J_FrmBid'
    time.sleep(1.1)
    try:#submit order #anoymous进入购买确认页面，匿名
        chrome.stop_client()
        anonybox = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("anony"))
        anonybox.click()
        chrome.execute_script("document.getElementById('anony').checked = true ")
    except:
        print 'fail to get element anony'
    time.sleep(0.9)
    try:#pay-for-another，代付款
        chrome.execute_script("document.getElementById('pay-for-another').checked = true")
    except:
        print 'fail to get element pay-for-another'
    try:#set count，设置数量
        cnt = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("quantityInput"))
        cnt.click()
        chrome.execute_script("document.getElementById('quantityInput').value = "+count)
    except:
        print 'fail to get element quantityInput'
    time.sleep(1.2)
    try:#submit，确认无误，购买
        sbt = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("J_OrderForm"))
        sbt.submit()
    except:
        print 'fail to get element performSubmit'
    try:#取消支付宝的新手导航
        chrome.execute_script("document.getElementById('J_guide_backgroundImg').style.display= 'none'")  
    except:
        print 'cancel alipay navigator failed'
    try:
        skip = chrome.find_element_by_name("skip")
        skip.click()
    except:
        print 'click skip fail'
    try:#click other-method-trigger  进入付款页面，点其他付款方式（代付链接）     
        anlink = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_element_by_id("other-method-trigger"))
        anlink.click()
    except:
        print 'fail to click other link'
    try:#click btn #name = orderId      
        anbtn = WebDriverWait(chrome, 10).until(lambda chrome : chrome.find_elements_by_class_name("ui-button-text"))
        anbtn[1].submit()
    except:
        print 'fail to click produce otherpay link btn'
    try:#get link text
        time.sleep(1.1)
        txt = chrome.find_element_by_xpath("//input[@id='link-value']")
        linktxt = txt.get_attribute('value')
        logit(linktxt, 'linktxt.log')
        print txt.get_attribute('value')
    finally:
        pass

    
def mainfun():
    xiaohaocount = int(config.get("global", "xiaohaocount"))
    item = config.get("global", "item")
    count = int(config.get("global", "count"))
    xiaohao = range(xiaohaocount)
    lpass = range(xiaohaocount)
    for i in range(xiaohaocount):
        xiaohao[i] = config.get("xiaohao", "hao"+str(i+1))    
        lpass[i] = config.get("lpass", "lpass"+str(i+1))    
        if(loginTb(xiaohao[i], lpass[i])):
            try:
                #print 'sure it'+xiaohao[i]+'::'+lpass[i]
                changeip()
                pai(item, count)               
                chrome.delete_all_cookies()
            except:
                print 'pai Error!!'

codec = 'gbk'
config = ConfigParser.ConfigParser()
initConfig('fast.ini')
config.read('fast.ini')
sn = config.get("global", "sn")
zhengban = checksn('fast', sn)
if(zhengban):
    #chrome = webdriver.Ie()
    chrome = webdriver.Chrome()
    mainfun()
    #chrome.close()
else:
    win32gui.MessageBox(0, '序列号错误，请联系客服QQ:894610580购买！'.decode('utf-8'), 'Notice!', 0)

